/**
 * Theme Store
 * 
 * 主题管理（明暗模式切换）
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export type Theme = 'light' | 'dark' | 'system';

interface ThemeState {
  /** 用户选择的主题 */
  theme: Theme;
  /** 实际应用的主题（解析 system 后） */
  resolvedTheme: 'light' | 'dark';
  /** 设置主题 */
  setTheme: (theme: Theme) => void;
  /** 切换主题 */
  toggleTheme: () => void;
}

/**
 * 获取系统主题偏好
 */
function getSystemTheme(): 'light' | 'dark' {
  if (typeof window === 'undefined') return 'dark';
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

/**
 * 解析主题（处理 system 模式）
 */
function resolveTheme(theme: Theme): 'light' | 'dark' {
  if (theme === 'system') {
    return getSystemTheme();
  }
  return theme;
}

/**
 * 应用主题到 DOM
 */
function applyTheme(theme: 'light' | 'dark') {
  const root = document.documentElement;
  
  // 移除旧的主题类
  root.classList.remove('light', 'dark');
  
  // 添加新的主题类
  root.classList.add(theme);
  
  // 更新 data 属性（用于 CSS 选择器）
  root.setAttribute('data-theme', theme);
}

/**
 * 主题 Store
 */
export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      theme: 'system',
      resolvedTheme: getSystemTheme(),

      setTheme: (theme: Theme) => {
        const resolved = resolveTheme(theme);
        applyTheme(resolved);
        set({ theme, resolvedTheme: resolved });
      },

      toggleTheme: () => {
        const current = get().resolvedTheme;
        const next = current === 'dark' ? 'light' : 'dark';
        applyTheme(next);
        set({ theme: next, resolvedTheme: next });
      },
    }),
    {
      name: 'cagent-theme',
      onRehydrateStorage: () => (state) => {
        // 恢复主题后立即应用
        if (state) {
          const resolved = resolveTheme(state.theme);
          applyTheme(resolved);
          state.resolvedTheme = resolved;
        }
      },
    }
  )
);

/**
 * 监听系统主题变化
 */
if (typeof window !== 'undefined') {
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    const store = useThemeStore.getState();
    if (store.theme === 'system') {
      const newTheme = e.matches ? 'dark' : 'light';
      applyTheme(newTheme);
      useThemeStore.setState({ resolvedTheme: newTheme });
    }
  });
}

/**
 * 初始化主题（在应用启动时调用）
 */
export function initializeTheme() {
  const store = useThemeStore.getState();
  const resolved = resolveTheme(store.theme);
  applyTheme(resolved);
  useThemeStore.setState({ resolvedTheme: resolved });
}

